<?php

/**
 * @class       LoginController
 * @ingroup     application.modules.user.controllers
 * @brief       Controller phục vụ cho việc login
 * @author      huytbt
 * @version     1.0
 * @date        2011-05-23
 */
class LoginController extends HController
{
	/**
	 * Returns the access rules for this controller.
	 * Override this method if you use the {@link filterAccessControl accessControl} filter.
	 * @return array list of access rules. See {@link CAccessControlFilter} for details about rule specification.
	 */
	/*public function accessRules()
	{
		return array(
			array('allow',  // allow all users anything not specified
				'users'=>array('*'),
			),
		);
	}*/
	
	public function actionIndex()
	{
		if (Yii::app()->request->isAjaxRequest) {
			$model = new LoginForm();
			
			if (isset($_POST['LoginForm'])) {
				$model->attributes = $_POST['LoginForm'];
				
				// validate user input and redirect to the previous page if valid
				if ($model->validate()) {
					if ($model->login()) {
						if (strpos(Yii::app()->user->returnUrl, '/index.php') !== false)
							$returnUrl = "/user/profile";
						else
							$returnUrl = Yii::app()->user->returnUrl;
						$this->renderJSON(self::SUCCESS, 'Login successful', array(
							'returnUrl' => $returnUrl
						));
					} else { // Authentication failed
						$this->renderJSON(self::ERROR, 'Authentication failed');
					}
				} else { // Validate failed
					$this->renderJSON(self::ERROR, 'Validate failed', $model->getErrors());
				}
			}
			
			$this->renderJSON(self::ERROR, 'Access denied');
		} else {
			// Kiểm tra nếu đăng nhập rồi chuyển trang
			if(!Yii::app()->user->isGuest)
			{
				if (strpos(Yii::app()->user->returnUrl, '/index.php') !== false)
						$this->redirect("/user/profile");
					else
						$this->redirect(Yii::app()->user->returnUrl);
			}
			
			$model = new LoginForm();
			
			// if it is ajax validation request
			if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
				echo CActiveForm::validate($model);
				Yii::app()->end();
			}
			
			// collect user input data
			if (isset($_POST['LoginForm'])) {
				$model->attributes = $_POST['LoginForm'];
				// validate user input and redirect to the previous page if valid
				if ($model->validate() && $model->login()) {
					$this->setRedirectOptions(array(
						"title" => UserModule::t('Login Success'),
						"message" => UserModule::t('The login was successful!'),
					));
					
					if (strpos(Yii::app()->user->returnUrl, '/index.php') !== false)
						$this->redirect("/user/profile");
					else
						$this->redirect(Yii::app()->user->returnUrl);
				}
			}
			
			$this->render('index', array('model' => $model));
		}
	}
}